package de.arndt_plc.wakeonmagic;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by MathiasAr on 22.10.2014.
 */
public class WakeOnLan {

    public static final int PORT = 9;

    public String Error;
    public final InetAddress IpAddress;

    public WakeOnLan(String bcast_ip) throws UnknownHostException {
        IpAddress = InetAddress.getByName(bcast_ip);
        Error = "";
    }

    public void wake(String mac) throws IOException {
        byte[] macBytes = getMacBytes(mac);
        byte[] bytes = new byte[6 + 16 * macBytes.length];
        for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) 0xff;
        }

        for (int i = 6; i < bytes.length; i += macBytes.length) {
            System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
        }

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, IpAddress, PORT);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
    }

    private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
        byte[] bytes = new byte[6];
        String mac = macStr.trim().replace(":", "").replace("-", "");
        if (mac.length() != 12)
            throw new IllegalArgumentException("Invalid MAC address");
        try {
            for (int i = 0; i < 6; ++i) {
                bytes[i] = (byte) Integer.parseInt(mac.substring(i * 2, i * 2 + 2), 16);
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid hex digit in MAC address.");
        }
        return bytes;
    }
}
